/**
 * @author gabrielepiva
 * @version 2
 *
 * \brief Funzioni per la gestione delle gallerie
 */

/**
 * Dichiarazione delle variabili globali
 */

var gallery_active_JSON		//JSON della galleria che stiamo visualizzando
var gallery_index_JSON		//JSON dell'indice delle gallerie (aggiornamento periodico)
var gallery_id				//identificatore della galleria attiva
var gallery_info			//Contiene il template html delle informazioni della galleria
var photos_active = new Array()	//Array contenente le foto della galleria. Indice dell'array è costituito dall'id della foto; valore true o false.
var editor_template			//Contiene il template html per effettuare l'editing di un'immagine

function set_gallery_index_JSON(){
	res = $.ajax({
		url: "scripts/get_json_gallery_list.php?id="+user_id,
		async: false
	}).responseText

	gallery_index_JSON = JSON.parse(res)
	return gallery_index_JSON
}

function galleries_index(){
	/*
	 * Elabora i dati contenuti in gallery_index_JSON
	 * 1)Se gallery_index_JSON è vuota set_gallery_index_JSON
	 * 2)Se gallery_info è vuota, eseguire la chiamata asincrona e salvare il responseText (Forse è piu corretto metterla in show_gallery())
	 * 3)Creare elenco dei link
	 */
	$("#str_bar").animate({
		"height":"30px"
	})
	$("#add_btn").attr("value",0)

	if(!gallery_index_JSON){
		gallery_index_JSON = set_gallery_index_JSON()
	}

	$("#content").html("")

	$.each(gallery_index_JSON.items,function(i,item){
		div = $("<div class='gallery_title'/>").attr({
			"id":"gallery_"+item.gallery_id
		})
		del = $("<div>").attr({
			"class": "photo_delete_button"
		}).click(function(){
			if(confirm("Sicuro di voler eliminare la galleria?") == true){
				$("#gallery_"+item.gallery_id).fadeOut()
			}
		}).appendTo(div)
		$("<a><h1>"+item.gallery_title+"</h1></a>").attr({
			"href": "scripts/get_json_gallery.php?id="+item.gallery_id,
			"title": "gallery/@"+item.gallery_id,
			"alt": item.gallery_title,
			"target": "content"
		}).click(function(event){
			event.preventDefault()
			var hash = this.title
			hash = hash.replace(/^.*#/, '');
			$.historyLoad(hash)
			gallery_id = item.gallery_id
		//	gallery_active_JSON_url =this.href
		}).appendTo(div)//.appendTo($("#content"))

		div.appendTo($("#content"))
	})
}

function gallery_info_get_template(){
	/*
	 * Questa funzione carica il template dove vengono visualizzate le informazioni sulla galleria
	 * La funzione viene chiamata una volta sola
	 */

//	console.debug("scarico il template per le info")
	res = $.ajax({
		url: "pages/gallery_info.php",
		async: false
	}).responseText
	return res

}

function gallery_info_fill_template(){
	/*
	 * Questa funzione elabora i dati di gallery_active_JSON e riempie il template
	 * Chiamare la funzione periodicamente
	 */

	$("#gallery_title").html(gallery_active_JSON.gallery_title.replace("<br />","\n"))
	$("#gallery_description").html(gallery_active_JSON.gallery_description)
	$("#gallery_owner").append(gallery_active_JSON.gallery_owner)
	$("#gallery_date").append($.aqStamp(gallery_active_JSON.gallery_date))
	$("#gallery_modified").append($.aqStamp(gallery_active_JSON.gallery_modified))
	$("#gallery_count_photos").append(gallery_active_JSON.gallery_items.length)

	/*
	 * Rendo i campi delle informazioni della galleria modificabili con tecnica inplace
	 */

	$("#gallery_title").editable(
		"scripts/update_gallery.php",{
			name: "gallery_title",
			height: "25px",
			width: "83%",
			onblur: "ignore",
			submit: "<img src='images/icon-ok.gif' />",
			cancel: "<img src='images/icon-undo.gif' />",
			submitdata:{
				"select_gallery": gallery_id,
				"xhr": "true"
				},
			data: function(value, settings) {
			   /* Convert <br> to newline. */
			   var retval = value.replace("/<br[\s\/]?>/gi", '\n');
			   return retval;
			},
			indicator: "Salvataggio in corso...",
			tooltip: "Click per modificare",
			callback: function(){
				gallery_index_JSON = set_gallery_index_JSON()
				gallery_active_JSON = 	get_JSON("scripts/get_json_gallery.php?id="+gallery_id)
			}
		}
	)
	$("#gallery_description").editable(
		"scripts/update_gallery.php",{
			name: "gallery_description",
			width: "83%",
			height: "250px",
			type: "textarea",
			data: function(value, settings) {
			   /* Convert <br> to newline. */
			   var retval = value.replace(/<br[\s\/]?>/gi, '\n');
			   return retval;
			},
			submit: "<img src='images/icon-ok.gif'  class='jeditable_button'/>",
			cancel: "<img src='images/icon-undo.gif'  class='jeditable_button'/>",
			onblur: "ignore",
			submitdata:{
				"select_gallery": gallery_id,
				"xhr": "true"
				},
			indicator: "Salvataggio in corso...",
			tooltip: "Click per modificare",
			callback: function(value){
				gallery_active_JSON = get_JSON("scripts/get_json_gallery.php?id="+gallery_id)
				gallery_info_fill_template()
			}
		}
	)/*.click(function(){
		$("textarea").rte({
			css: "lib/rte.css"
		})
	})*/
}


function gallery_thumbs(){
	/*
	 * Elaboro i dati di gallery_active_JSON
	 */
	gallery_thumbnails = $("<div class='gallery_thumbnails'/>")
	$.each(gallery_active_JSON.gallery_items,function(i,item){

		photo_viewer = $("<div/>").attr({
			"id":"photo_"+item.photo_id,
			"class":"photo_viewer",
			"n": i,
			"selected": "false",
			"photo_id": item.photo_id
		}).click(function(){
			if($(this).attr("selected") == "false"){
				$(this).attr("selected","true")
			}else{
				$(this).attr("selected","false")
			}
			editor()
			$("#left_wrapper_"+item.photo_id).toggleClass("left_wrapper_active")
			$("#thumbnail_wrapper_"+item.photo_id).toggleClass("thumbnail_wrapper_active")
			$("#right_wrapper_"+item.photo_id).toggleClass("right_wrapper_active")

		})

		div_left_wrap = $("<div/>").attr({
			"class": "left_wrapper",
			"id": "left_wrapper_"+item.photo_id
		})

		div_thumbnail = $("<div/>").attr({
			"class": "thumbnail_wrapper",
			"id": "thumbnail_wrapper_"+item.photo_id
		})

		div_right_wrap = $("<div/>").attr({
			"class": "right_wrapper",
			"id": "right_wrapper_"+item.photo_id
		})


		photo_thumbnail = $("<img/>").attr({
			"src": "photos/"+item.photo_hash+".thumb.png"
		})
		div_left_wrap.appendTo(photo_viewer)
		div_thumbnail.appendTo(photo_viewer)
		photo_thumbnail.appendTo(div_thumbnail)
		div_right_wrap.appendTo(photo_viewer)

		photo_viewer.appendTo(gallery_thumbnails)

	gallery_thumbnails.appendTo($("#content"))
	})
}

function show_gallery(){
	/*
	 * Elabora il contenuto di gallery_active_json
	 * 1)Scrive le informazioni sulla galleria
	 * 2)Genera le thumbnails della galleria
	 */
//	console.debug("Controllo gallery_active_JSON...")

	if(gallery_active_JSON){
//		console.debug("Controllo che sia in possesso del JSON giusto: '"+gallery_id+"'")
		if(gallery_id == gallery_active_JSON.gallery_id){
//			console.debug("Possiedo il JSON giusto")
		}else{
//			console.debug("Non possiedo il JSON giusto, me lo scarico...")
			gallery_active_JSON = get_JSON("scripts/get_json_gallery.php?id="+gallery_id)
		}
	}else{
//		console.debug("Non ho il JSON della galleria "+gallery_id+"...")
		gallery_active_JSON = get_JSON("scripts/get_json_gallery.php?id="+gallery_id)
	}

	if(!gallery_info){
		gallery_info = gallery_info_get_template()
	}
	$("#content").html(gallery_info)
	gallery_info_fill_template()
	gallery_thumbs()

	$("#add_btn").val(gallery_id).attr("href","#gallery/@"+gallery_id+"/add")

}

function gallery_str_bar(){
	$("#str_bar").html("")
	div = $("<div/>").attr({
		"class": "buttons",
		"id": "gallery_buttons"
	})

	add_btn = $("<input/>").attr({
		"type": "image",
		"src": "images/icon-add.png",
		"value": "0",
		"id": "add_btn",
		"href":"#gallery/add"
	}).css({
		"float": "left",
		"margin-right": "5px",
		"width" : "16px"
	}).click(function(event){
		event.preventDefault()
		if(this.value == 0){
			window.location.replace("#gallery/add")
		}else{
			window.location.replace("#gallery/@"+gallery_id+"/add")
		}
	})

	back_btn = $("<input/>").attr({
		"type": "image",
		"src": "images/icon-back.gif"
	}).css({
		"float": "left",
		"margin-right": "5px",
		"width" : "16px"
	}).click(function(){
		history.go(-1)
	})
	div.appendTo($("#str_bar"))
	add_btn.appendTo(div)
	if($("#str_bar").css("height") == "280px"){
		$("#str_bar").animate({
			height: "30px",
		})
	}
	return div
}

function add_photo_to_gallery(){
	if($("#str_bar").css("height") == "30px"){
		$("#str_bar").animate({
			height: "280px",
		})
	}
	$.ajax({
		url: "pages/form_upload.php",
		success: function(responseText){
			$("#add_btn").fadeOut()
			$("#str_bar").append(responseText)
			$("#select_gallery").attr("value",gallery_id)

			$("#upload_form").ajaxForm({
				beforeSubmit: function(){
					if($("#pic_controller").fieldValue() == "false"){
						$("#pic_selector img").fadeIn(function(){$(this).fadeOut(1000)})
						return false
					}else{
						$("#pic").css({
							"border": "auto"
						})
					}
					if($("#photo_title").fieldValue() == ""){
						$("#photo_title").focus().css({
							"border": "1px solid red"
						})
						$("#title_selector img").fadeIn(function(){$(this).fadeOut(1000)})
						return false;
					}else{
						$("#photo_title").css({
							"border": "auto"
						})
					}
				},
				success: function(){
					gallery_active_JSON = ""
					window.location.replace("#gallery/@"+gallery_id)
				}
			})

			$("#pic").MultiFile({
				onFileAppend:function(){
					$("#pic_controller").attr({
						"value": "true"
					})
					$("#pic_selector").fadeOut(function(){
						$("#list").fadeIn()
					})
				},
				onFileRemove: function(){
					$("#pic_controller").attr({
						"value": "false"
					})
					$("#list").fadeOut(function(){
						$("#pic_selector").fadeIn()
					})
				},
				list: "#fileList"
			})
			$("#undo_btn").click(function(){
				window.location.replace("#gallery/@"+gallery_id)
			})
		}
	})
	/*
	*/
}
function add_gallery(){
	$.ajax({
		url: "pages/form_gallery.php",
		success: function(responseText){
			$("#add_btn").fadeOut()
			$("#str_bar").append(responseText)
			$(":submit").click(function(event){
				event.preventDefault()
				action = $("#gallery_galleries").attr("action").toString()
				method = $("#gallery_galleries").attr("method")
				queryString = $("#gallery_galleries").serialize()
				$.ajax({
					url: action,
					type: method,
					data: queryString,
					success: function(msg){
						gallery_str_bar
						gallery_index_JSON= ""
						window.location.replace("#gallery/@"+msg+"/add")
					}
				})
			})
			$("#undo_btn").click(function(){
				window.location.replace("#gallery")
			})
		}
	})
}
function editor(){
	/*
	 * legge il contenuto di photos_active
	 *
	 */
	if (!editor_template) {
		editor_template = $.ajax({
			url: "pages/editor.html",
			async: false
		}).responseText
		console.debug(editor_template)
	//	$("#content").append(editor_template)
	}

	if($("#editor").length<1){
		$("#content").append(editor_template)
	}

	photos_active.splice(0)

	$.each($("div.photo_viewer[selected=true]"),function(){
		photos_active.push($(this).attr("n")) //cambio photo_id. Usando n posso recuperare velocemente i dati dal json caricato
	})

	if (photos_active.count() == 0) {
		$("#editor").fadeOut()
	//	$("#photo_title").text("")
	//	$("#photo_description").text("")
	}else{
		if(photos_active.count() == 1){

			$(".zoom_button").remove()
			zoom_button = $("<div />").attr({
				"id": "zoom_button_"+gallery_active_JSON.gallery_items[photos_active[0]].photo_id,
				"class": "zoom_button"
			}).click(function(){
				jQuery.facebox({ image: "photos/"+gallery_active_JSON.gallery_items[photos_active[0]].photo_filename })
			})
			$(document).bind("keydown","space",function(){
				jQuery.facebox({ image: "photos/"+gallery_active_JSON.gallery_items[photos_active[0]].photo_filename })
				$(document).bind("keyup","space",function(){
					$.facebox.close()
				})
			//	$(document).unbind("keydown","space",function(){
			})

			$("#editor_middle").html("")
			$("#delete_button").remove()

			photo_title = $("<p/>").attr({
				"id" : "photo_title",
				"class": "photo_title"
			}).editable("scripts/update_photo.php",{
				type: "text",
				name: "photo_title",
				data: function(value, settings) {
				   /* Convert <br> to newline. */
				   var retval = value.replace(/<br[\s\/]?>/gi, '\n');
				   return retval;
				},
				id: "#thumbnail_description_edit_"+gallery_active_JSON.gallery_items[photos_active[0]].photo_id,
				indicator: "Salvataggio in corso...",
				tooltip: "Click per modificare",
				onblur: "ignore",
				submit: "<img src='images/icon-ok.gif' class='jeditable_button'/>",
				cancel: "<img src='images/icon-undo.gif' class='jeditable_button'/>",
				width: "82%",
				height: "22px",
				submitdata: {"photo_id":gallery_active_JSON.gallery_items[photos_active[0]].photo_id},
				callback: function(){
					gallery_active_JSON = get_JSON("scripts/get_json_gallery.php?id=" + gallery_id)
				}
			}).html(gallery_active_JSON.gallery_items[photos_active[0]].photo_title)

			photo_description = $("<p/>").attr({
				"id":"photo_description"
			}).editable("scripts/update_photo.php",{
				type: "textarea",
				onblur: "ignore",
				name: "photo_description",
				data: function(value, settings) {
				   /* Convert <br> to newline. */
				   var retval = value.replace(/<br[\s\/]?>/gi, '\n');
				   return retval;
				},
				id: "#thumbnail_description_edit_"+gallery_active_JSON.gallery_items[photos_active[0]].photo_id,
				indicator: "Salvataggio in corso...",
				tooltip: "Click per modificare",
				submit: "<img src='/images/icon-ok.gif' class='jeditable_button'/>",
				cancel: "<img src='images/icon-undo.gif' class='jeditable_button' />",
				width: "99%",
				height: "250px",
				submitdata: {"photo_id":gallery_active_JSON.gallery_items[photos_active[0]].photo_id},
				callback: function(){
					gallery_active_JSON = get_JSON("scripts/get_json_gallery.php?id=" + gallery_id)
				}
			}).html(gallery_active_JSON.gallery_items[photos_active[0]].photo_description)

			photo_gallery = $("<span/>").text(gallery_active_JSON.gallery_title).editable("scripts/update_photo.php",{
					id: "gallery_selector",
					data: create_select_galleries(),
					name: "gallery_selector",
					type: "select",
					submit: "<img src='/images/icon-ok.gif' class='jeditable_button'/>",
					cancel: "<img src='images/icon-undo.gif' class='jeditable_button' />",
					onblur: "ignore",
					onsubmit: function(){
						/*
						 * Scrivo il json dei dati da inviare al server
						 */
						ser = this.serializeArray()
						console.debug(ser[0].value)
						if (ser[0].value != gallery_id) {
							send_JSON = '{"gallery_id":"' + ser[0].value + '","items":['
							$.each(photos_active, function(i, photo){
								//send_JSON += '{"photo_id":"' + gallery_active_JSON.gallery_items[photos_active[i]].photo_id + '"}'
								send_JSON += gallery_active_JSON.gallery_items[photos_active[i]].photo_id
								if (i != photos_active.count() - 1) {
									send_JSON += ","
								}
								$("div[photo_id=" + gallery_active_JSON.gallery_items[photos_active[i]].photo_id + "]").fadeOut("slow").remove()
							})
							send_JSON += "]}"
							$.ajax({
								url: "scripts/multi_update_photo.php",
								data: "json=" + send_JSON,
								dataType: "json",
								type: "POST",
								complete: function(msg){
									console.debug(msg)
								}
							})
							photos_active.splice(0)
							//gallery_active_JSON = get_JSON("scripts/get_json_gallery.php?id=" + gallery_id)
						//	show_gallery()
						}else{

						}
						$("#editor").fadeOut()
					}
				})

			photo_extra = $("<p/>").attr({
				"class":"photo_extra"
			}).text("Dimensioni immagine: "+gallery_active_JSON.gallery_items[photos_active[0]].photo_width+" x "+gallery_active_JSON.gallery_items[photos_active[0]].photo_height+" px")

			photo_date = $("<p/>").attr({
				"class": "photo_extra"
			}).text("Caricata "+$.aqStamp(gallery_active_JSON.gallery_items[photos_active[0]].photo_date))

			$("<h1>Titolo</h1>").appendTo($("#editor_middle"))
			photo_title.appendTo($("#editor_middle"))

			$("<h1>Descrizione</h1>").appendTo($("#editor_middle"))
			photo_description.appendTo($("#editor_middle"))

			$("<span/>").text("Galleria: ").appendTo($("#editor_middle"))
			photo_gallery.appendTo($("#editor_middle"))


			photo_extra.appendTo($("#editor_middle"))
			photo_date.appendTo($("#editor_middle"))

			photo_delete = $("<div/>").attr({
				"alt": "delete",
				"class" :"photo_delete_button",
					"id":"delete_button"
			}).click(function(){
				if(confirm("Sei sicuro di voler eliminare quest'immagine?") == true){
				/*
				 * STEP 1: Chiamata alla pagina scripts/delete_photo.php
				 * STEP 2: Ricaricamento Json galleria
				 */
				res = $.ajax({
					url: "scripts/delete_photo.php",
					type: "POST",
					data: {"photo_id":gallery_active_JSON.gallery_items[photos_active[0]].photo_id},
					success: function(response){
						if(response == "304"){
							display_error_message("Errore durante la cancellazione dell'immagine... Provare in un secondo momento")
							return
						}
						$("#photo_"+gallery_active_JSON.gallery_items[photos_active[0]].photo_id).fadeOut(function(){
							$(this).remove()
							$("#editor").fadeOut()
						})
						gallery_active_JSON = get_JSON("scripts/get_json_gallery.php?id="+gallery_id)
					}
				})
			}
			}).appendTo($("#editor_bottom"))
			zoom_button.appendTo($("#editor_bottom"))

			if($("#editor").css("display") == "none"){
				$("#editor").fadeIn("slow")
			}
		}
		if(photos_active.count() >1){
				$(".zoom_button").remove()
				$("#photo_title").remove()
				$("#photo_description").remove()
				$("#editor_middle h1").remove()
				$("#delete_button").remove()

				$("<p>").attr({
					"id": "photo_description"
				}).html(gallery_active_JSON.gallery_title).editable("scripts/update_photo.php",{
					id: "gallery_selector",
					data: create_select_galleries(),
					name: "gallery_selector",
					type: "select",
					data: function(value, settings) {
					   /* Convert <br> to newline. */
					   var retval = value.replace(/<br[\s\/]?>/gi, '\n');
					   return retval;
					},
					submit: "<img src='/images/icon-ok.gif' class='jeditable_button'/>",
					cancel: "<img src='images/icon-undo.gif' class='jeditable_button' />",
					onblur: "ignore",
					onsubmit: function(){
						/*
						 * Scrivo il json dei dati da inviare al server
						 */
						ser = this.serializeArray()
						console.debug(ser[0].value)
						if (ser[0].value != gallery_id) {
							send_JSON = '{"gallery_id":"' + ser[0].value + '","items":['
							$.each(photos_active, function(i, photo){
								//send_JSON += '{"photo_id":"' + gallery_active_JSON.gallery_items[photos_active[i]].photo_id + '"}'
								send_JSON += gallery_active_JSON.gallery_items[photos_active[i]].photo_id
								if (i != photos_active.count() - 1) {
									send_JSON += ","
								}
								$("div[photo_id=" + gallery_active_JSON.gallery_items[photos_active[i]].photo_id + "]").fadeOut("slow").remove()
							})
							send_JSON += "]}"
							$.ajax({
								url: "scripts/multi_update_photo.php",
								data: "json=" + send_JSON,
								dataType: "json",
								type: "POST",
								complete: function(msg){
									console.debug(msg)
								}
							})
							photos_active.splice(0)
							//gallery_active_JSON = get_JSON("scripts/get_json_gallery.php?id=" + gallery_id)
						//	show_gallery()
						}else{

						}
						$("#editor").fadeOut()
					}
				}).prependTo($("#editor_middle"))

				photo_delete = $("<div/>").attr({
					"alt": "delete",
					"class" :"photo_delete_button",
					"id":"delete_button"
				}).click(function(){
					if (confirm("Stai cercando di fare uno spicinio di foto, sei sicuro?") == true) {
						/*
						 * STEP 1: Chiamata alla pagina scripts/delete_photo.php
						 * STEP 2: Ricaricamento Json galleria
						 */
						send_JSON = '{"items":['
						$.each(photos_active, function(i, photo){
							//send_JSON += '{"photo_id":"' + gallery_active_JSON.gallery_items[photos_active[i]].photo_id + '"}'
							send_JSON += gallery_active_JSON.gallery_items[photos_active[i]].photo_id
							if (i != photos_active.count() - 1) {
								send_JSON += ","
							}
							$("div[photo_id=" + gallery_active_JSON.gallery_items[photos_active[i]].photo_id + "]").fadeOut("slow").remove()
						})
						send_JSON += "]}"
						$.ajax({
							url: "scripts/multi_update_photo.php",
							data: "json=" + send_JSON,
							dataType: "json",
							type: "POST",
							complete: function(msg){
								console.debug(msg)
							}
						})
						photos_active.splice(0)
					}
				}).appendTo($("#editor_bottom"))

				$("<p>").attr({
					"id":"photo_title"
				}).html(photos_active.count()+" foto selezionate").prependTo("#editor_middle")

				$("p.photo_extra").remove()
		}
	}
	$("#close_button").click(function(){
		photos_active.splice(0)
		show_gallery()
	})
}

function create_select_galleries(){
	/*
	 * Elabora gallery_index_JSON e costruisce un array da utilizzare per creare una select
	 */
	if(!gallery_index_JSON){
		gallery_index_JSON = set_gallery_index_JSON()
	}
	select = "{ "

	$.each(gallery_index_JSON.items,function(i,item){
		select += "'"+item.gallery_id+"':'"+item.gallery_title+"',"

	})
	select += "'selected':'"+gallery_id+"'"
	select += "}"
//	select['selected'] = gallery_id
	return select
}
